import os
import random
import time
from datetime import datetime

from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.http import JsonResponse
from django.shortcuts import render, redirect, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from tourist_spot import models

from tourist_spot.models import TouristArticle


def travel_article_homepage(request):
    user_info = request.session.get('info')  # 使用.get()避免KeyError
    if user_info:
        user = models.RegularUser.objects.filter(username=user_info.get('username')).first()

    articles = models.TouristArticle.objects.all().order_by('-created_at')

    return render(request, 'travel_article_homepage.html', {"user": user,"articles":articles})


def save_cover_image(user, image_file, request):
    # 验证文件是否存在
    if not image_file:
        raise ValueError("没有上传封面图片")

    # 创建存储目录：/img/users/<id>/article/<文章标题>/cover/
    article_title = request.POST.get("title").strip().replace(" ", "_")  # 获取文章标题并处理空格
    user_dir = os.path.join(
        settings.MEDIA_ROOT,
        'img',
        'users',
        f'{user.id}',  # 直接使用用户ID，不加user_前缀
        'article',
        article_title,
        'cover'
    )
    os.makedirs(user_dir, exist_ok=True)  # 自动创建目录

    # 固定命名为cover.jpg
    filename = "cover.jpg"

    # 完整保存路径
    save_path = os.path.join(user_dir, filename)

    # 保存文件（分块写入适合大文件）
    with open(save_path, 'wb+') as destination:
        for chunk in image_file.chunks():
            destination.write(chunk)

    # 返回相对路径（去掉MEDIA_ROOT前缀）
    return os.path.join(
        'img',
        'users',
        f'{user.id}',  # 直接使用用户ID
        'article',
        article_title,
        'cover',
        filename
    )


def save_tourist_images(user, image_files, request):
    saved_paths = []

    # 如果没有上传内容图片，返回空列表
    if not image_files:
        return saved_paths

    # 创建存储目录：/img/users/<id>/article/<文章标题>/content/
    article_title = request.POST.get("title").strip().replace(" ", "_")  # 获取文章标题并处理空格
    user_dir = os.path.join(
        settings.MEDIA_ROOT,
        'img',
        'users',
        f'{user.id}',  # 直接使用用户ID
        'article',
        article_title,
        'content'
    )
    os.makedirs(user_dir, exist_ok=True)

    # 处理每张图片
    for index, img in enumerate(image_files, start=1):
        # 固定命名为content1.jpg, content2.jpg...
        filename = f"content{index}.jpg"

        # 完整保存路径
        save_path = os.path.join(user_dir, filename)

        # 保存文件
        with open(save_path, 'wb+') as destination:
            for chunk in img.chunks():
                destination.write(chunk)

        # 记录相对路径
        saved_paths.append(
            os.path.join(
                'img',
                'users',
                f'{user.id}',  # 直接使用用户ID
                'article',
                article_title,
                'content',
                filename
            )
        )

    return saved_paths

@csrf_exempt  # 临时禁用CSRF验证，开发阶段方便测试，生产环境应移除
def add_travel_article(request, nid):
    user_info = request.session.get('info')  # 使用.get()避免KeyError
    if user_info:
        user = models.RegularUser.objects.filter(username=user_info.get('username')).first()
    if request.method == "GET":
        return render(request, 'add_travel_article.html', {"user": user})

    author = models.RegularUser.objects.filter(id=nid).first()
    title = request.POST.get("title")
    cover_img = request.FILES.get("img")
    days = request.POST.get("days")
    season = request.POST.get("season")
    type = request.POST.get("type")
    state = request.POST.get("state")
    country = request.POST.get("country")
    city = request.POST.get("city")
    destination = request.POST.get("destination")
    date = request.POST.get("date")
    introduction = request.POST.get("introduction")
    content = request.POST.get("content")
    images = request.FILES.getlist('travelImages')  # 注意这里改为FILES.getlist

    tags_str = request.POST.get("tags", "")  # 获取原始标签字符串，如"自由行,自驾游"

    # 分割并清理标签
    tags_list = [tag.strip() for tag in tags_str.split(',') if tag.strip()]

    # 保存图片并获取路径
    cover_path = save_cover_image(author, cover_img, request)
    content_paths = save_tourist_images(author, images, request)

    article = models.TouristArticle.objects.create(
        author=author,
        title=title,
        days=days,
        season=season,
        type=type,
        state=state,
        country=country,
        city=city,
        destination=destination,
        date=datetime.strptime(date, '%Y-%m-%d').date(),
        introduction=introduction,
        content=content,
        cover_path=cover_path,
        content_paths=content_paths
    )

    for tag_name in tags_list:
        # 获取或创建标签对象（自动去重）
        tag, _ = models.Tag.objects.get_or_create(name=tag_name)
        article.tags.add(tag)

    return JsonResponse({
        'status': 'success',
        'article_id': article.id,
        'message': '游记创建成功'
    })


def travel_article_detail(request,nid):


    article = models.TouristArticle.objects.filter(id=nid).first()
    user = models.RegularUser.objects.filter(id=article.author_id).first()

    return render(request,'travel_article_detail.html',{"article":article,"user":user})




















